package com.wyj.wuliwuli.shiro;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.wyj.wuliwuli.common.AjaxResult;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class CustomRolesAuthorizationFilter extends RolesAuthorizationFilter {

    @Override
    protected Subject getSubject(ServletRequest request, ServletResponse response) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JWTToken token = new JWTToken(authorization);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        Subject subject = super.getSubject(request, response);
        subject.login(token);
        return subject;
    }

    @Override
    public boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) {

        Subject subject = null;
        try {
            subject = getSubject(req, resp);
        } catch (Exception e) {
            response401(req, resp, e);
        }

        String[] rolesArray = (String[]) mappedValue;
        //如果没有角色限制，直接放行
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }
        for (int i = 0; i < rolesArray.length; i++) {
            //若当前用户是rolesArray中的任何一个，则有权限访问
            if (subject.hasRole(rolesArray[i])) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        //处理跨域问题，跨域的请求首先会发一个options类型的请求
        if (servletRequest.getMethod().equals(HttpMethod.OPTIONS.name())) {
            return true;
        }
        boolean isAccess = isAccessAllowed(request, response, mappedValue);
        if (isAccess) {
            return true;
        }
        servletResponse.setCharacterEncoding("UTF-8");
        Subject subject = getSubject(request, response);
        PrintWriter printWriter = servletResponse.getWriter();
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setHeader("Access-Control-Allow-Origin", servletRequest.getHeader("Origin"));
        servletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        servletResponse.setHeader("Vary", "Origin");
        servletResponse.setStatus(401);
        String respStr;

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setCode(HttpStatus.FORBIDDEN.value());
        if (subject.getPrincipal() == null) {
            respStr = JSONObject.toJSONString(ajaxResult);
        } else {
            respStr = JSONObject.toJSONString(ajaxResult);
        }
        printWriter.write(respStr);
        printWriter.flush();
        servletResponse.setHeader("content-Length", respStr.getBytes().length + "");
        return false;
    }


    private void response401(ServletRequest req, ServletResponse resp, Exception ex) {

        if (ex.getCause() instanceof TokenExpiredException) {

            throw new AuthenticationException("tokenexpired");
        } else if(ex.getCause() instanceof NullPointerException){

            throw new AuthenticationException("tokenmissing");
        } else if (ex instanceof SignatureVerificationException) {

            throw new AuthenticationException("signatureerror");
        } else if(ex instanceof AuthenticationException){

            throw new AuthenticationException("tokeninvalid");
        }
    }
}
